-module(pidReuse).

-export([start/0, run/0, echo/0, communicator/1]).

-define(N1, n1@localhost).
-define(N2, n2@localhost).

start() ->
    spawn(?N1, ?MODULE, run, []).

run() ->
    erlang:process_flag(trap_exit, true),
    Pids = lists:map(fun(_N) ->
        Pid1 = spawn_link(?N2, erlang, self, []),
        spawn(?N2, erlang, halt, []),
        timer:sleep(2000),
        Pid1
        end, lists:seq(1, 3)),
    lists:foreach(fun(Pid) ->
        receive {'EXIT', Pid, _} -> ok end end, Pids),
    spawn(?N2, ?MODULE, echo, []),
    communicator(Pids).

echo() ->
    receive {From, N} -> From ! {self(), (N+1)} end.

communicator(Pids) ->
    lists:foreach(fun(Pid) ->
        io:format("Tring to communicate with ~p~n(~p)~n", 
            [Pid, term_to_binary(Pid)]),
        Pid ! {self(), 5},
        receive {Pid2, N} ->
            io:format("Receive ~p from ~p~n(~p)~n", 
                [N, Pid2, term_to_binary(Pid2)])
        after 2000 ->
            io:format("No reply~n")
        end
    end, Pids).
